﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;

namespace SkypeCore
{
	public class MessagesManager
	{
		private readonly string _databasePath;

		public MessagesManager(string databasePath)
		{
			_databasePath = databasePath;
		}

		public IEnumerable<SkypeMessage> Get(string contactName, string accountName)
		{
			using (var connection = DatabaseConnection.Get(_databasePath))
			{
				//var selfName = new ContactsManager(_databasePath).GetSelfName().First();
				var commandText = string.Format("select body_xml, timestamp, id, author from messages where author = '{1}' " +
					"union select body_xml, timestamp, id, author from messages where author = '{0}' " +
												"and convo_id in (select convo_id from messages where author = '{1}')", accountName, contactName);
				using (var command = new SQLiteCommand(commandText, connection))
				{
					using (var reader = command.ExecuteReader())
					{
						while (reader.Read())
						{
							var message = new SkypeMessage
							              	{
							              		Author = reader.GetString(3),
							              		Date = (new DateTime(1970, 1, 1, 0, 0, 0)).AddSeconds(reader.GetInt32(1)),
							              		Message = reader.GetValue(0) as string,
							              		Id = reader.GetInt32(2)
							              	};
							if (string.IsNullOrEmpty(message.Message))
								continue;
							yield return message;
						}
					}
				}
			}
		}

		public void Delete(int id)
		{
			using (var connection = DatabaseConnection.Get(_databasePath))
			{
				var commandText = string.Format("delete from messages where id = {0}", id);
				using (var command = new SQLiteCommand(commandText, connection))
					command.ExecuteNonQuery();
			}
		}

	}
}
